//
//  PhoneVerifyViewController.m
//  Growth
//
//  Created by 洪波 陈 on 6/9/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "PhoneVerifyViewController.h"

#import "PublicMethodEngine.h"

#import "WebRequest.h"
#import "CJSONSerializer.h"
#import "RegexKitLite.h"

#import "NotificationEngine.h"

static NSString *phoneNumKey = @"PhoneNumKey";
static NSString *phoneAuthCodeKey = @"PhoneAuthCodeKey";
static NSString *vertifySendDateKey = @"VertifySendDateKey";

static WebConnectionArray *verifySMS_connection;
static WebConnectionArray *verifyNickName_connection;
static WebConnectionArray *phoneRegiste_connection;

@interface PhoneVerifyViewController ()

@end

@implementation PhoneVerifyViewController

@synthesize phoneLabel;

@synthesize phoneNumStr;
@synthesize authCode;

@synthesize authCodeField;
@synthesize nickNameField;

- (void)dealloc
{
    [phoneLabel release];
    
    [phoneNumStr release];
    [authCode release];
    
    [authCodeField release];
    [nickNameField release];
    
    if (phoneRegiste_connection != nil) {
        phoneRegiste_connection.connectionDelegate = nil;
        [phoneRegiste_connection release];
        phoneRegiste_connection = nil;
    }
    if (verifySMS_connection != nil) {
        verifySMS_connection.connectionDelegate = nil;
        [verifySMS_connection release];
        verifySMS_connection = nil;
    }
    if (verifyNickName_connection != nil) {
        verifyNickName_connection.connectionDelegate = nil;
        [verifyNickName_connection release];
        verifyNickName_connection = nil;
    }
    
    [super dealloc];
}

- (id)initWithPhone:(NSString *)phoneStr
{
    self = [super init];
    if (self) {
        self.phoneNumStr = phoneStr;
    }
    
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"新用户注册";
    
    self.phoneLabel.text = [NSString stringWithFormat:@"您的手机号:%@",phoneNumStr]; 

    NSString *savePhone = [[NSUserDefaults standardUserDefaults] valueForKey:phoneNumKey];
    if ([savePhone isEqualToString:phoneNumStr]) {
        CLog(@"exit");
        authCode = [[NSString alloc] initWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:phoneAuthCodeKey]];

    }
    else {
        CLog(@"no phone exit");
        [self getPhoneVertifyWith:nil];
        [LoadingView hideWithAnimated:NO];
    }
    

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - verify

- (IBAction)getPhoneVertifyWith:(id)sender
{
    NSString *lastDateStr = [[NSUserDefaults standardUserDefaults] valueForKey:vertifySendDateKey];
    NSString *dateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:[NSDate date]];
    NSDate *date = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:dateStr];
    
    if (lastDateStr != nil) {
    
        NSDate *lastDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:lastDateStr];
        NSTimeInterval distance = [lastDate timeIntervalSinceDate:date];

        distance = fabsf(distance);
        
        CLog(@"date %@   last Date %@", date, lastDate);
        CLog(@"distance %f", distance);
        
        if (distance <60) {
            int waitTime = 60 -distance;
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME *2 message:[NSString stringWithFormat:@"请%d秒后再试！", waitTime]];
            
            return;
        }
        else {
            CLog(@"can send again!");
        }
        
        
    }
    
    CLog(@"can send!");
    
    CLog(@"new date %@", date);
    CLog(@"new date str %@", dateStr);
    [[NSUserDefaults standardUserDefaults] setValue:dateStr forKey:vertifySendDateKey];

    [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:phoneNumKey];
    [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:phoneAuthCodeKey];
    
    authCode = nil;
    //发送验证码
    NSMutableURLRequest * request = [WebRequest phoneVertifySMSRequesetWith:phoneNumStr];
    CLog(@"request %@", request);
    if (verifySMS_connection != nil) {
        verifySMS_connection.connectionDelegate = nil;
    }
    verifySMS_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
}


-(void)verifyNickName:(NSString *)nickName{ //验证nickname
    
    _isNickNameCorrect = NO;
    if (NETWORK_STATUS_LOADING) {
        NSMutableURLRequest *request = [WebRequest verifyNickNameRequest:nickName];
        
        CLog(@"request %@", request);
        if (verifyNickName_connection != nil) {
            verifyNickName_connection.connectionDelegate = nil;
        }
        verifyNickName_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }
    
    
}




#pragma mark - Web Connection delegate
- (void)connectionArraySuccess:(NSDictionary *)dict  connectionURL:(NSString *)url
{
    CLog(@"dict :%@", dict);
    NSRange range = [url rangeOfString:@"sms/send"]; 
    
    if (range.length > 0)  {
        
        NSDictionary *resultDict = [dict objectForKey:@"object"];
        
         NSString *errorCode = [resultDict objectForKey:@"errorCode"];
        if (![errorCode isMemberOfClass:[NSNull class]]
            && [errorCode intValue] == 0) {
            authCode = [[NSString alloc] initWithFormat:@"%@",[resultDict objectForKey:@"authCode"]] ;
            NSString *errorCode = [resultDict objectForKey:@"errorCode"];
            
            [[NSUserDefaults standardUserDefaults] setValue:phoneNumStr forKey:phoneNumKey];
            [[NSUserDefaults standardUserDefaults] setValue:authCode forKey:phoneAuthCodeKey];
            
            CLog(@"auth code message %@", authCode);
            CLog(@"errorCode message %@", errorCode);
        }
        else{
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME *2 message:@"获取验证码错误，请返回重试！"];
            
            NSString *errorReason = [resultDict objectForKey:@"errorReason"];
            CLog(@"errorReason message %@", errorReason);

        } 
    }
    
    //昵称验证
    range = [url rangeOfString:@"verify/nickname"];
    if (range.length > 0)  {
        
        CLog(@"verify nickName %@",[dict objectForKey:@"object"] );
        
        if ([[dict objectForKey:@"object"] boolValue]== TRUE) { 
            _isNickNameCorrect = TRUE;       
            
            [self registerAccount];
            
            return;
        }
        else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"昵称错误" message:@"该昵称已经被注册啦，换一个吧！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
        
        
    }

    
    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/user/regist",UCENTERBASEURL]])  {
        
        if([dict objectForKey:@"object"]){
            
            NSDictionary *userInfo = [dict objectForKey:@"object"];
            
            NSInteger errorCode = [[userInfo objectForKey:@"errorCode"] intValue];
            
            if((errorCode == 0 || errorCode == 6) &&[[userInfo allKeys] containsObject:@"userId"]){
                
                
                [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"userId"] forKey:@"userId"];
                [[NSUserDefaults standardUserDefaults]setValue:[userInfo objectForKey:@"userNickname"] forKey:@"userName"];
                [[NSUserDefaults standardUserDefaults]setValue:[userInfo objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
                
                [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"Ucenter-Code"] forKey:@"Ucenter-Code"];
                [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"Ucenter-VerifyCode"] forKey:@"Ucenter-VerifyCode"];
                
                [[NotificationEngine sharedNotificationEngine] postDeviceToken];
                
                [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:phoneNumKey];
                [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:phoneAuthCodeKey];
                
                
                [self registerSuccess ];
            }
            else {
                NSString *errorReason = [userInfo objectForKey:@"errorReason"];
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"注册错误，请重试！" message:errorReason delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                
                [alertView show];
                [alertView release];
            }

        }
        
    }
}

- (void)connectionArrayError:(NSError *)error
{
    [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"网络错误，请重试！"];
}

#pragma mark - Action
- (IBAction)loginAction:(id)sender
{
    CLog(@"Login!");
    
    [nickNameField resignFirstResponder];
    [authCodeField resignFirstResponder];
    
    //验证码
    NSString *authCodeEnter = [authCodeField text];
    if (authCode == nil) {
        [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"验证码获取失败，请返回重试！" duration:DEFAULT_LOADING_TIME];
        
        return;
    }
    
    if (![authCode isEqualToString:authCodeEnter]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"验证码错误" message:@"请仔细核对手机验证码，重新输入！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        _isAuthCodeCorrect = NO;
        return;
    }
    else {
        _isAuthCodeCorrect = YES;
    }
    
    //昵称长度限制
    BOOL isNickName = [nickNameField.text isMatchedByRegex:REGEX_NICKNAME];
    if (!isNickName) {
        
        
        _isNickNameCorrect = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"昵称错误" message:@"昵称必须是2~10位的中文、英文、数字！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;    

    }
    else {
        if (!_isNickNameCorrect) {
            [self verifyNickName:nickNameField.text];
        }
        
    }
    
}

- (void)registerAccount
{
    
    if (_isNickNameCorrect) {
        
        if (NETWORK_STATUS_LOADING) {
            
            
            NSArray *keys = [NSArray arrayWithObjects:@"appId",@"account",@"nickname", nil];
            
            
            NSArray *objects;
            objects = [NSArray arrayWithObjects:[NSNumber numberWithInt:APP_ID],phoneNumStr,nickNameField.text, nil];
            
            NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
            
            NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
            CLog(@"theBodyString  %@", theBodyString);
            
            
            NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
            
            NSMutableURLRequest * request = [WebRequest registRequestWith:jsonData];
            
            CLog(@"request %@", request);
            if (phoneRegiste_connection != nil) {
                phoneRegiste_connection.connectionDelegate = nil;
            }
            phoneRegiste_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
            
            
            _isPostRegist = TRUE;
        }
        
    }
    
}

- (void)registerSuccess
{
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:REGIST_LOGIN_KEY];
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"isFirstInApp"];
    
    NSString *uidStr = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] stringValue];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: uidStr, @"uid", nil];
    [MobClick event:MobClick_Register_Phone attributes:dict];
    
    [self dismissModalViewControllerAnimated:YES];
}


#pragma mark - TextField Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField.tag == 1) {
        [nickNameField becomeFirstResponder];
    }
    else if (textField.tag == 2) {
        [textField resignFirstResponder];
    }

    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField.tag == 1) {
        CLog(@"authcode change!");
        _isAuthCodeCorrect = NO;
    }
    else if (textField.tag == 2) {
        CLog(@"nickname change!");
        _isNickNameCorrect = NO;
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 1) {
        CLog(@"auth code change!");
        _isAuthCodeCorrect = NO;
    }
    if (textField.tag == 2) {
        CLog(@"nickname change!");
        _isNickNameCorrect = NO;
    }
    
    
    return YES;
}


@end
